/**
 * 
 */
package com.java.controller.front;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import javax.print.DocFlavor.STRING;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Pattern.Flag;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.java.entity.User;
import com.java.mapper.UserMapper;
import com.java.service.UserService;
import com.java.service.impl.UserServiceImpl;
import com.java.utils.Validator;
import com.java.utils.md5Utils;
import com.mysql.jdbc.Field;

/**
 * @author Kidney 创建时间：2019年1月22日 上午7:08:18 Description:
 *         http://localhost:8080/huahua//user/selectAll.shtml
 */

@Controller
@RequestMapping("/user/")
public class UserController {

	@Autowired
	private UserServiceImpl us;

	/**
	 * 用户登录
	 */
	@RequestMapping("login")
	public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password,
			@RequestParam(name = "remember-me", required = false) boolean rememberme, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		HttpSession session = request.getSession();
		User user = new User();
		user.setUserName(username);
		// md5
		String p1 = md5Utils.md5(password);
		user.setPassword(p1);

		// Session中存好的验证码数值
		String piccode = (String) request.getSession().getAttribute("piccode");
		// 前端用户输入的验证码值
		String verifycode = request.getParameter("verifycode");

		String newV = verifycode.toUpperCase();

		User result = us.login(user, rememberme, response);
		if (result != null && newV.equals(piccode)) {
			ModelAndView mAndView = null;
			// 登录之前地址
			String callback = (String) session.getAttribute("callback");
			session.removeAttribute("callback"); // 获取之后移除
			// 基本路径
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();

			if (StringUtils.isNotBlank(callback) && username.equals("admin")) {
				System.out.println("admin");
				String[] urls = callback.split(basePath);
				if (urls.length == 2 && StringUtils.isNotBlank(urls[1])) {
					mAndView = new ModelAndView("redirect:" + urls[1]);
				} else {
					mAndView = new ModelAndView(" /WEB-INF/admin/adminHome.jsp");
				}
			} else if (username.equals("admin")) {
				mAndView = new ModelAndView("/WEB-INF/admin/adminHome.jsp");
			}

			if (StringUtils.isNotBlank(callback) && username.equals("admin") == false) {
				String[] urls = callback.split(basePath);
				if (urls.length == 2 && StringUtils.isNotBlank(urls[1])) {
					mAndView = new ModelAndView("redirect:" + urls[1]);
				} else {

					mAndView = new ModelAndView("/pages/front/index.jsp");
				}
			} else if (username.equals("admin") == false) {
				mAndView = new ModelAndView("/pages/front/index.jsp");
			}

			session.setAttribute("user", result); // 登录成功之后加入session中
			redirectAttributes.addFlashAttribute("user", result);

			return mAndView;
		} else {
			JOptionPane.showMessageDialog(null, "登陆错误");
			return new ModelAndView("/pages/front/login.jsp");
		}
	}

	/**
	 * 用户登出
	 */
	@RequestMapping("logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mAndView = new ModelAndView("redirect:/pages/front/login.jsp");
		us.logout(request, response);
		return mAndView;
	}

	/**
	 * 用户注册
	 */
	// public ModelAndView register(String username, String password, String
	// tele, String address,String dizhi,
	@RequestMapping(value = "register")
	public ModelAndView register(@Valid User newUser, BindingResult errorResult, HttpServletRequest request,
			HttpServletResponse response) {
		//找是否有重复用户名
		User checkUser = us.selectByName(newUser.getUserName());
		
		// Session中存好的验证码数值
		String piccode = (String) request.getSession().getAttribute("piccode");
		// 前端用户输入的验证码值
		String verifycode = request.getParameter("verifycode");

		String newV = verifycode.toUpperCase();

		System.out.println(newV);

		System.out.println(newUser);

		ModelAndView mav = new ModelAndView();
		mav.setViewName("/pages/front/register.jsp");

		Map<String, Object> resultMap = Validator.fieldValidator(errorResult);

		if (resultMap == null) {// success!
			if (checkUser == null) {
				if (newV.equals(piccode)) {

					// 添加用户
					User user = new User();
					user.setTele(newUser.getTele());
					user.setAddress(newUser.getAddress());
					String newPass = md5Utils.md5(newUser.getPassword());
					user.setPassword(newPass);
					user.setUserName(newUser.getUserName());
					user.setDizhi(newUser.getDizhi());

					int flag = us.insertSelective(user);

					// 注册成功跳转到主页面
					if (flag == 1) {

						mav.addObject("status", "注册成功");

					} else {

						mav.addObject("status", "注册失败");
					}
				}

				else {
					// 注册失败跳转到错误页面
					mav.addObject("error", "验证码错误");
				}

			}

		}else{
			
			mav.addObject("errorMessage", resultMap);
			
			mav.addObject("userInfo", newUser);
			
		}

		if (checkUser != null) {

			mav.addObject("error", "用戶名重複");
		}

		return mav;
	}

	/**
	 * 用户主页
	 */
	@RequestMapping("home")
	public ModelAndView userIndex() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/pages/front/userHome.jsp");
		return mav;
	}

	/**
	 * 用户密码修改
	 */
	@RequestMapping("changePassword")
	public ModelAndView changePassword(String password1, String password2, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		Cookie[] cookies = request.getCookies();

		if (password1.equals(password2)) {
			String username = null;

			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
					username = cookie.getValue();

				}
			}

			User selectedUser = us.selectByName(username);
			int selectedId = selectedUser.getUserId();

			User record = new User();
			record.setUserId(selectedId);
			record.setPassword(md5Utils.md5(password1));
			int flag = us.updateByPrimaryKeySelective(record);

			mav.addObject("username", username);
			mav.addObject("time", new Date());
			mav.addObject("flag", 1 == flag ? "修改成功" : "修改失败");
			mav.setViewName("/pages/front/changePassword.jsp");
		} else {
			mav.addObject("time", new Date());
			mav.getModel().put("error", "密码不相等");
			mav.setViewName("/pages/front/changePassword.jsp");
		}
		return mav;
	}

	/**
	 * 用户信息修改
	 */
	@RequestMapping("changeInfo")
	public ModelAndView changeInfo(String address, String tele, HttpServletRequest request,
			HttpServletResponse response) {

		ModelAndView mav = new ModelAndView();
		Cookie[] cookies = request.getCookies();
		String username = null;

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				username = cookie.getValue();
			}
		}

		User selectedUser = us.selectByName(username);
		int selectedId = selectedUser.getUserId();
		User record = new User();

		record.setUserId(selectedId);
		record.setAddress(address);
		record.setTele(tele);

		int flag = us.updateByPrimaryKeySelective(record);
		mav.addObject("username", username);
		mav.addObject("time", new Date());
		mav.addObject("flag", 1 == flag ? "成功" : "失败");
		mav.setViewName("/pages/front/changeInfo.jsp");

		return mav;
	}

	/*
	 * (non-Javadoc)
	 * http://localhost:8080/huahua//user/insertSelective.shtml?userName=asdasd&
	 * password=12312321&address=asdasdasd&tele=123456789
	 * 
	 * @see com.java.mapper.UserMapper#insertSelective(com.java.entity.User)
	 */
	@ResponseBody // 用来返回特定的值
	@RequestMapping("insertSelective")
	public int insertSelective(String userName, String password, String address, String tele) {

		User record = new User();
		record.setAddress(address);
		record.setPassword(password);
		record.setTele(tele);
		record.setUserName(userName);

		return us.insertSelective(record);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.java.mapper.UserMapper#updateByPrimaryKeySelective(com.java.entity.
	 * User)
	 */

	@ResponseBody // 用来返回特定的值
	@RequestMapping("updateByPrimaryKeySelective")
	public int updateByPrimaryKeySelective(String userName, String password, String address, String tele) {
		User record = new User();
		record.setAddress(address);
		record.setPassword(password);
		record.setTele(tele);
		record.setUserName(userName);
		return us.updateByPrimaryKeySelective(record);
	}

	@ResponseBody // 用来返回特定的值
	@RequestMapping("selectByUser")
	public User selectByUser(String userName, String password) {
		User record = new User();
		record.setPassword(password);
		record.setUserName(userName);
		return us.selectByUser(record);
	}

	@ResponseBody // 用来返回特定的值
	@RequestMapping("selectByName")
	public User selectByName(String userName) {
		// TODO Auto-generated method stub
		return us.selectByName(userName);
	}

	@ResponseBody // 用来返回特定的值
	@RequestMapping("getInfo")
	public ModelAndView getInfo(String userName, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		Cookie[] cookies = request.getCookies();

		String username = null;

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				username = cookie.getValue();

			}
		}

		User selectedUser = us.selectByName(username);
		int selectedId = selectedUser.getUserId();

		User u = new User();
		u.setUserId(selectedId);

		mav.addObject("user", u);
		mav.setViewName("/pages/front/infoManagement.jsp");

		return mav;

	}

	@ResponseBody // 用来返回特定的值
	@RequestMapping("recharge")
	public ModelAndView recharge(float deposit, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		Cookie[] cookies = request.getCookies();

		String username = null;

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				username = cookie.getValue();
			}
		}

		User selectedUser = us.selectByName(username);
		int selectedId = selectedUser.getUserId();

		User u = new User();
		u.setUserId(selectedId);

		User u2 = us.selectByPrimaryKey(selectedId);

		float originDeposit = u2.getDeposit();
		System.out.println(originDeposit);
		u.setDeposit(originDeposit + deposit);

		int flag = us.updateByPrimaryKeySelective(u);

		if (flag == 1) {
			mav.addObject("status", "200");

		} else {
			mav.addObject("status", "失败");

		}
		mav.setViewName("/pages/front/infoManagement.jsp");
		return mav;

	}

	@ResponseBody // 用来返回特定的值
	@RequestMapping("test9")
	public ModelAndView test9() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/pages/front/registerSuccess.jsp");
		return mav;

	}

}
